-- DungeonStatM
-- created by panyl
-- 迷宫数据统计

module("DungeonStatM", package.seeall);

local overLayer = {};
local gridStat  = {};
local layerStat = {};

-- 模块初始化操作
function init()
    overLayer = {};
    gridStat = {};

    EventMgr.removeAll("DungeonStatM");
    EventMgr.register("DungeonStatM", event.LEAVE_DUNGEON, function()
        -- 离开地牢，清空
        overLayer = {};

        gridStat = {};

        tempStat = {};

        layerStat = {};
    end);

    -- 关注层数回退（大地之门等技能）的事件
    EventMgr.register("DungeonStatM", event.BACK_FLOOR, function()
        -- 清空
        overLayer = {};

        tempStat = {};
    end);
end

function clearTempStat()
    overLayer = {};

    tempStat = {};
end

-- 更新下统计
function updateStat(stat)
    gridStat = stat;

    layerStat = {};

    -- 已遍历的楼层清空
    overLayer = {};

    tempStat = {};
end

-- 单独统计
function doStat(class, count, element)
    tempStat[class] = iif(tempStat[class], tempStat[class], 0) + count;
end

-- 当前层据统计
function currStat(class, count, element)
    -- (玩家客户端用不到此数据，给验证客户端用的)
    table.insert(layerStat, {["class"] = class, ["element"] = element, ["count"] = count, });

    -- 统计
    gridStat[class] = tonumber(gridStat[class]) + count;

    -- 临时数据统计需要去掉
    tempStat[class] = tonumber(tempStat[class]);
    tempStat[class] = tempStat[class] - count;
    if tempStat[class] < 0 then
        tempStat[class] = 0;
    end
end

-- 做每层的统计
function doLayerStat(layer, elements)
    -- 如果该层已经统计过了
    if overLayer[layer] then
        return;
    end

    overLayer[layer] = true;

    for _, elem in pairs(elements) do
        local class = table.keys(elem)[1];
        local element = elem[class];

        doStat(class, 1, element);
    end
end

function queryStat()
    return gridStat;
end

function queryLayerStat()
    return layerStat;
end

-- 获取某格子已经出现的次数
function getStatCount(class)
    return (gridStat[class] or 0) + (tempStat[class] or 0);
end

-- 获取所有的格子统计
function getTotalStat()
    local ret = {};

    for k, v in pairs(gridStat) do
        ret[k] = tonumber(ret[k]) + gridStat[k];
    end

    for k, v in pairs(tempStat) do
        ret[k] = tonumber(ret[k]) + tempStat[k];
    end

    return ret;
end

function getTempStat()
    return tempStat;
end
